/*
  Author: Sheila Tabuena
  Filename: dbUtilities.js
  Date Created: MAY-02-2009

  Contains functions to interact with MySQL database via php servlets. Supports both 
  the PABC website notice table, plus a simple table maintenance page. Functions include:

   makeAndSendQuery(url,callBack,sql) -- sends "sql" to servlet located at "url" via ContentLoader,
                    also supplies "callBack" for successful results
 
   errorFunction()--callback function from ContentLoader for errors, displays error messages

   buildDbTables(callBack)--Builds all the tables in the database 
                            (after dropping them if they exist)
   goodBuildFunction()--callback function for successful table creation
 
   addNotice(newNotice,callBack)--adds a new notice "newNotice" to the 
                    notices table, calls "callBack" if successfull
   emptyNotice(callBack)--empties out the notice table (truncate), calls 
                   "callBack" if successful
 
   getNotices(callBack)--retrieves all the notices the notices table, 
                  passes a callback routine to handle results
   getTableArray(response)--turns XML in "response" into a two dimensional array 
                 "table", to make display easier returns array "table"
   refreshNotice()--gets a fresh load from the notices db table and displays it.

   doAdd() -- adds a new announcement to the notices table
   
   addslashes(str)--equivalent function to php addslashes, got it off the web,
               takes argument "str" and returns string with special characters 
               like quotes etc escaped with slashes for mysql
   stripslashes(str)--equivalent function to php stripslashes, got it off the web,
               takes argument "str" and returns string with special characters 
               like quotes etc unescaped by removing the slashes.
    */

// Builds all the tables in the database (after dropping them if they exist) 
function buildDbTables(callBack)
{
	url = "http://ctislab.fhda.edu/~tabuenas/php/buildDB.php"
  var contentLoader = new net.ContentLoader(url,callBack,errorFunction);
}

// callback function for successful table creation
function goodBuildFunction()
{
  var ansNode = document.getElementById("result");
  ansNode.firstChild.data = "Database Table notices rebuilt";
}



// empties out the notice table (truncate), calls "callBack" if successful
function emptyNotice(callBack)
{
	url = "http://ctislab.fhda.edu/~tabuenas/php/anyQuery.php"
  var sql = "q=TRUNCATE TABLE notices;";
  makeAndSendQuery(url,callBack,sql);
}

// retrieves all the notices the notices table, passes a callback routine to handle results
function getNotices(callBack)
{
	url = "http://ctislab.fhda.edu/~tabuenas/php/anyQuery.php"
  var sql = "q=SELECT DATE(posted), text FROM notices ORDER BY posted DESC;";
  makeAndSendQuery(url,callBack,sql);
}

// sends "query" to servlet located at "url" via ContentLoader, passes "callBack" for success
function makeAndSendQuery(url,callBack,query) 
{
  var contentLoader = new net.ContentLoader(url,callBack,errorFunction,"POST",query);
}

// callback function from ContentLoader for errors, displays error messages
function errorFunction()
{
  var eNode = document.getElementById("notices");
  addJqNode(eNode,"p","noticeError","ERROR ACCESSING DATABASE: " + this.req.responseText);
}

// turns XML in "response" into a two dimensional array "table", to make display easier
// returns array "table"
function getTableArray(response)
{
  var table = [];
  var rowArray = response.getElementsByTagName("row");
  for (i=0;i<rowArray.length;++i)
  {
  	var colArray = rowArray[i].getElementsByTagName("col");
  	var col = [];
    for (j=0;j<colArray.length;++j)
    {
    	if (colArray[j].firstChild != null)
    	{
         col[j] = colArray[j].firstChild.data;
       }
    }
    table[i] = col;
  }
  return table;
}

// puts database rows contained in responseXML into in a html table
function doNoticeTable() 
{
	currentAnswer = getTableArray(this.req.responseXML);
  var notNode = document.getElementById("notices");
  notNode.innerHTML = "";
  tabNode = addJqNode(notNode,"table","responseTable","");
  for (i=0;i< currentAnswer.length; ++ i)
  {
    trNode = addJqNode(tabNode,"tr",("tr"+i),"");
    for (j=0;j<currentAnswer[i].length; ++j)
    {
    	noticeText = stripslashes(currentAnswer[i][j])
      addJqNode(trNode,"td",("td"+i+j),noticeText);
    }
  } 
}

// adds a new announcement to the notices table
function doAdd() 
{
  var inputNode = document.getElementById("uaInput");
  notice = inputNode.value;
  inputNode.value="";
  if (notice != null & notice.length > 0)
    addNotice(notice,refreshNotice);
}

// adds a new notice "newNotice" to the notices table, calls "callBack" if successfull
function addNotice(newNotice,callBack)
{
	url = "http://ctislab.fhda.edu/~tabuenas/php/anyQuery.php";
  var sql = "q=INSERT INTO notices (text) VALUES ('" + addslashes(newNotice) + "');";
  makeAndSendQuery(url,callBack,sql);
}

// gets a fresh load from the notices db table and displays it.
function refreshNotice()
{
  getNotices(doNoticeTable);
}

/* equivalent function to php addslashes, got it off the web
  takes argument "str" and returns string with special characters 
   like quotes etc escaped with slashes for mysql */

function addslashes(str) 
{
   str=str.replace(/\'/g,'\\\'');
   str=str.replace(/\"/g,'\\"');
   str=str.replace(/\\/g,'\\\\');
   str=str.replace(/\0/g,'\\0');
   return str;
}

/* equivalent function to php stripslashes, got it off the web
   takes argument "str" and returns string with special characters 
   like quotes etc unescaped by removing slashes */
function stripslashes(str) 
{
   str=str.replace(/\\'/g,'\'');
   str=str.replace(/\\"/g,'"');
   str=str.replace(/\\\\/g,'\\');
   str=str.replace(/\\0/g,'\0');
   return str;
}

/* This function is called by dbBike onload, it builds the page, including headers,
   radio buttons, and action buttons.  */
function buildDBPage()
{
  var divNode = document.getElementById("container");
  addNode(divNode,"h1","h1_1","Database Utilities");
  divNode = addNode(divNode,"div","main","");
  hNode = addNode(divNode,"h2","h2_1","Functions: ");
  showNode = addNode(divNode,"button","getButton","Get Notices");
  showNode.setAttribute("onclick","getNotices(doNoticeTable);");
  emptyNode = addNode(divNode,"button","emptyButton","Empty Notice Table");
  emptyNode.setAttribute("onclick","emptyNotice(refreshNotice);");
  createNode = addNode(divNode,"button","createButton","Create Tables");
  createNode.setAttribute("onclick","buildDbTables(goodBuildFunction);");
  addNode(divNode,"h4","h_4","Text for notice: "); 
  addNode(divNode,"input","uaInput","");
  noticeNode = addNode(divNode,"button","uaAdd","Add Notice");
  noticeNode.setAttribute("onclick","doAdd();");
  addNode(divNode,"div","result","Result: ");
  addNode(divNode,"div","notices","Here are notices");

}

function getEvent() {
	var divNode = document.getElementById("event");
	console.log ("HELLO");
}
